/*
created by chuyoujun at 2018-10-18
工具文件

* */
const untils = {};
import Vue from 'vue';
//设置本地缓存
untils.setLocalStorage = function (key, value, isJson) {
  if (window.localStorage) {
    if (isJson) {
      value = JSON.stringify(value);
    }
    window.localStorage[key] = value;
  }
};

//获取本地缓存
untils.getLocalStorage = function (key, isJson) {
  if (window.localStorage) {
    var value = window.localStorage[key] || "";
    if (isJson && value) {
      value = JSON.parse(value);
    }
    return value;
  }
  return '';
};

//清除本地缓存
untils.removelocalStorage = function (key) {
  if (window.localStorage) {
    window.localStorage.removeItem(key);
  }
};

//设置运行时缓存setSessionStorage
untils.setSessionStorage = function (key, content, isJson) {
  if (window.sessionStorage) {
    if (isJson) {
      content = JSON.stringify(content);
    }
    window.sessionStorage[key] = content;
    return true;
  }
};

//获取运行时缓存getSessionStorage
untils.getSessionStorage = function (key, isJson) {
  if (window.sessionStorage) {
    var value = window.sessionStorage[key] || '';
    if (value == 'undefined') {
      survey.log('缓存的 ' + key + ': 为undefined');
      return value;
    }
    if (value && isJson) {
      value = JSON.parse(value);
    }
    return value;
  }
  return '';
};

//清除运行时缓存removeSessionStorage
untils.removeSessionStorage = function (key) {
  if (window.sessionStorage) {
    window.sessionStorage.removeItem(key);
  }
};

//增加cookie
untils.addCookie = function (name, value, expiresHours) {
  var cookieString = name + "=" + escape(value);
  //判断是否设置过期时间
  if (expiresHours) {
    if (expiresHours > 0) {
      var date = new Date();
      date.setTime(date.getTime + expiresHours * 3600 * 1000);
      cookieString = cookieString + "; expires=" + date.toGMTString();
    }
  }
  document.cookie = cookieString;
};

//获取某个cookie
untils.getCookie = function (cookie_name, decode) {
  decode = decode || true;
  var allcookies = document.cookie;
  var cookie_pos = allcookies.indexOf(cookie_name);
  var value = '';
  if (cookie_pos > -1) {
    cookie_pos += cookie_name.length + 1;
    var cookie_end = allcookies.indexOf(";", cookie_pos);
    if (cookie_end == -1) {
      cookie_end = allcookies.length;
    }
    value = allcookies.substring(cookie_pos, cookie_end);
    if (decode) {
      try {
        value = decodeURIComponent(value);
      } catch (e) {
        console.log(e);
        return "";
      }
    }
  }
  return value;
};

//设置某个cookie
untils.setCookie = function (cookie_name, cookie_value, domain, isencode, expTime) {
  var exp = new Date();
  var expires = "";
  if (expTime) {
    exp.setTime(exp.getTime() + expTime);
    expires = ";expires=" + exp.toGMTString();
  }
  if (!domain) {
    domain = document.domain;
    if (/^[a-z]/i.test(document.domain)) {
      domain = document.domain.substring(document.domain.indexOf("."));
    }
  }

  isencode = typeof isencode == 'undefined' ? true : isencode;
  if (isencode) {
    cookie_value = encodeURIComponent(cookie_value);
  }
  document.cookie = cookie_name + "=" + cookie_value + "; path=/; domain=" + domain + ";" + expires;
};
//阻止弹框滚动
untils.toggleBody = function (isPin) {
  if (isPin) {

    document.body.style.height = '100vh';

    document.body.style['overflow-y'] = 'hidden'
  }

  else {

    document.body.style.height = 'unset';

    document.body.style['overflow-y'] = 'auto'

  }

};

//删除cookie
untils.deleteCookie = function (name) {
  var date = new Date();
  date.setTime(date.getTime() - 10000);
  document.cookie = name + "=v; expires=" + date.toGMTString();
};

//接口地址
untils.server = function () {
  return window.location.protocol + '//' + window.location.host;
};

//自定义弹窗
untils.Alert = function (opt) {
  var opt1 = {
    title: "操作提醒",
    content: "",
    closeBtn: true,
    buttonText: ['取消', '确定'],
    callback: function (number) {
    }
  };
  opt = Object.assign(opt1, opt);
  var temp = Vue.extend({
    template:
      '<div class="component-mask" id="untils-alert">' +
      '    <div class="com-alert">' +
      '      <div class="alert-tips">' +
      '      ' + opt.title +
      '      </div>' +
      '<div class="alert-content" v-html="opt.content"></div>' +
      '      <div class="alert-button">' +
      '        <a class="alert-cancle"    @click="callback(0)" v-show="opt.closeBtn">{{opt.buttonText[0]}}</a>' +
      '        <a class="alert-sure"      @click="callback(1)" >{{opt.buttonText[1]}}</a>' +
      '      </div>' +
      '    </div>' +
      '  </div>',
    methods: {
      callback(n) {
        opt.callback && opt.callback(n);
        untils.toggleBody(0);
        setTimeout(() => {
          document.getElementById('untils-alert').remove()
        }, 200)
      }
    },
    data() {
      return {
        opt: opt
      }
    }
  });
  var $temp = new temp();
  untils.toggleBody(1);
  document.body.appendChild($temp.$mount().$el);
};

untils.systemTips = function (html, time = 2000) {

  const temp = Vue.extend({
    template: '<div class="system-tips" id="untils-tips" v-html="html"></div>',
    methods: {},
    data() {
      return {
        html: html,
        time: time
      }
    },
    mounted() {
      setTimeout(() => {
        document.getElementById('untils-tips').remove();
      }, this.time)
    }
  });
  var $tempTips = new temp();
  untils.toggleBody(1);
  document.body.appendChild($tempTips.$mount().$el);
};

//loading显示
untils.showLoading = function () {
  var vueTemp = Vue.extend({
    template: ' <div class="loading">' +
      '    <div class="spinner">' +
      '      <div class="spinner-container container1">' +
      '        <div class="circle1"></div>' +
      '        <div class="circle2"></div>' +
      '        <div class="circle3"></div>' +
      '        <div class="circle4"></div>' +
      '      </div>' +
      '      <div class="spinner-container container2">' +
      '        <div class="circle1"></div>' +
      '        <div class="circle2"></div>' +
      '        <div class="circle3"></div>' +
      '        <div class="circle4"></div>' +
      '      </div>' +
      '      <div class="spinner-container container3">' +
      '        <div class="circle1"></div>' +
      '        <div class="circle2"></div>' +
      '        <div class="circle3"></div>' +
      '        <div class="circle4"></div>' +
      '      </div>' +
      '    </div>' +
      '  </div>'
  });
  var $temp = new vueTemp();
  untils.closeLoading();
  document.body.appendChild($temp.$mount().$el);
};
//loading隐藏
untils.closeLoading = function () {
  document.getElementsByClassName('loading')[0] && document.getElementsByClassName('loading')[0].remove();
};

untils.getErrorRes = function (res) {
  let errorMsg;
  if (res.status == 500) {
    errorMsg = '服务器产生内部错误';
  } else if (res.status == 403) {
    errorMsg = '请求不允许';
  } else if (res.status == 404) {
    errorMsg = '没有发现文件、查询或URl';
  } else if (res.status == 502 || res.status == 503) {
    errorMsg = '服务暂时不可用，请重试！';
  } else {
    errorMsg = '访问错误！';
  }
  return errorMsg;
};

/*
     method     图片压缩
     @param    url   图片链接
     @param    obj   设置图片
     @param    callback    压缩完成回调
*/
untils.zipImg = function (url, obj, calback) {
  var img = new Image();
  img.src = url;
  var base64 = '';
  img.onload = function () {
    var that = this;
    // 默认按比例压缩
    var w = that.width,
      h = that.height,
      scale = w / h;
    w = obj.width || w;
    h = obj.height || (w / scale);
    var quality = 0.7;  // 默认图片质量为0.7
    //生成canvas
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    // 创建属性节点
    var anw = document.createAttribute("width");
    anw.nodeValue = w;
    var anh = document.createAttribute("height");
    anh.nodeValue = h;
    canvas.setAttributeNode(anw);
    canvas.setAttributeNode(anh);
    ctx.drawImage(that, 0, 0, w, h);
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality;
    }
    // quality值越小，所绘制出的图像越模糊
    base64 = canvas.toDataURL('image/jpg', quality);
    calback(base64)
  };

};

/*
     method     图片上传
     @param    ev   事件对象
     @param    callback    上传完成回调
*/
untils.upLoadImg = function (ev, callback) {
  var target = ev.target;
  var file = target.files[0];
  let fileType = file.type;
  if (!(fileType == 'image/jpeg' || fileType == 'image/png')) {
    untils.Alert({
      html: '请上传图片文件'
    });
    return false;
  }
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function () {
    var result = this.result;
    callback(result)
  }
};

/*
     method        异步加载js文件
     @param        className        加载script标签类名
     @param        url              加载文件路径
     @param        callback         加载完成回调
*/

untils.loadAsycJs = function (className, url, callback) {
  let name = document.getElementsByClassName(className)[0];
  if (!name) {
    let scriptEle = document.createElement('script');
    scriptEle.src = url;
    scriptEle.className = className;
    scriptEle.onload = function () {
      callback && callback();
    };
    document.body.appendChild(scriptEle);
  } else {
    callback && callback();
  }
};

/*
     method        异步加载css文件
     @param        className        加载script标签类名
     @param        url              加载文件路径
     @param        callback         加载完成回调
*/

untils.loadAsycCss = function (className, url) {
  let name = document.getElementsByClassName(className)[0];
  if (!name) {
    let scriptEle = document.createElement('link');
    scriptEle.href = url;
    scriptEle.rel = 'stylesheet';
    scriptEle.className = className;
    document.head.appendChild(scriptEle);
  }
};

/*
     method     查看pdf文件
     @param     elementId     展示pdf父容器id名
     @param     url           加载文件路径
     @param     scale         描绘文件比例
     @param     showLoading   是否显示loading
*/
untils.showPdf = function ({elementId, url, scale, showLoading}) {
  showLoading && untils.showLoading();
  untils.loadAsycJs('PDFWORK', untils.server() + '/static/pdf.js', () => {
    PDFJS.workerSrc = '/static/pdf.worker.js';
    var loadingTask = PDFJS.getDocument(url);
    loadingTask.promise.then(function (pdf) {
      var pageNumber = pdf.numPages;
      for (var i = 1; i <= pageNumber; i++) {
        pdf.getPage(i).then(function (page) {
          console.log('Page loaded');
          var scale = scale || .7;
          var viewport = page.getViewport(scale);
          // var canvas = document.getElementById('canvas');
          var canvas = document.createElement('canvas');
          var context = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;
          document.getElementById(elementId).appendChild(canvas);
          var renderContext = {
            canvasContext: context,
            viewport: viewport
          };
          var renderTask = page.render(renderContext);
          renderTask.then(function () {
            untils.closeLoading();
            console.log('Page rendered');
          });
        });
      }
    }, function (reason) {
      console.error(reason);
    });

  });


};

untils.getPlatform = function () {
  var platforms = {
    amazon_fireos: /cordova-amazon-fireos/,
    android: /Android/,
    ios: /(iPad)|(iPhone)|(iPod)/,
    blackberry10: /(BB10)/,
    blackberry: /(PlayBook)|(BlackBerry)/,
    windows8: /MSAppHost/,
    windowsphone: /Windows Phone/
  };

  for (var key in platforms) {
    if (platforms[key].exec(navigator.userAgent)) {
      return key;
    }
  }
  return "";
}


untils.getMathRand = function () {
  var _val = '';
  if (typeof num !== 'number') {
    return '00000';
  }
  for (var i = 0; i < num; i++) {
    _val += Math.floor(Math.random() * 10);
  }
  return _val;
};
untils.getRandomCode = function () {
  var date = new Date();
  return date.getTime() + untils.getMathRand(5);
};

untils.getSignature = function (randomcode) {
  var openname = 'fwd';
  var openkey = 'fairyland';
  return openname + openkey + randomcode;
};

/*
     method     返回一段时间的彼标准格式
     @param     startTime     开始时间
     @param     endTime           结束时间
     @param     showLoading
*/
untils.returnDate = function (startTime, endTime) {
  let startTamp = new Date(startTime).getTime();
  let endTamp = new Date(endTime).getTime();
  let show = true;

  let leftTime = endTamp - startTamp;
  if (leftTime <= 0) {
    show = false
  }
  var days = Math.floor(leftTime / (24 * 3600 * 1000)).toString();
  var hourLeft = leftTime % (24 * 60 * 60 * 1000);
  var hours = Math.floor(hourLeft / (3600 * 1000)).toString();
  var minuetLeft = hourLeft % (3600 * 1000);
  var minutes = Math.floor(minuetLeft / (60 * 1000)).toString();
  var secondLeft = minuetLeft % (60 * 1000);
  var seconds = Math.round(secondLeft / 1000).toString();
  return {
    days: days >= 10 ? days : '0' + days,
    hours: hours >= 10 ? hours : '0' + hours,
    minutes: minutes >= 10 ? minutes : '0' + minutes,
    seconds: seconds >= 10 ? seconds : '0' + seconds,
    show: show
  };

};
/*
     method     返回一段时间的倒计时
     @param     startTime     开始时间
     @param     endTime       结束时间
     @param     callback      回调
*/
untils.countDown = function (startTime, endTime, callback) {
  let startTamp = new Date(startTime).getTime();
  let endTamp = new Date(endTime).getTime();

  let timer = setInterval(() => {
    startTamp += 1000;
    let leftTime = endTamp - startTamp;
    let result = untils.returnDate(startTamp, endTamp);
    if (leftTime <= 0) {
      result.show = false;
      clearInterval(timer);
    }
    callback(result)
  }, 1000)

};


export default untils;

